package com.asion.qkan.ui.model;

import com.asion.qkan.api.ServiceApi;
import com.asion.qkan.db.Music;
import com.asion.qkan.entry.MusicBean;
import com.asion.qkan.jiguangtuisong.ExampleApplication;
import com.asion.qkan.ui.contract.MusicContract;
import com.asion.qkan.utils.retrofitCache.SetCacheUtils;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by asion on 16-10-12.
 */

public class MusicModel implements MusicContract.Model {

    @Override
    public void getMusicListDatas(String string, MusicContract.OnMusicGetListener onMusicGetListener) {

        ExampleApplication.getMusicDao().deleteAll();

        new Retrofit.Builder()
                .baseUrl("http://music.163.com/")
                .client(SetCacheUtils.setCache())
                .addConverterFactory(GsonConverterFactory.create())
                .build()
                .create(ServiceApi.class)
                .getMusicCommend(string)
                .enqueue(new Callback<MusicBean>() {
                    @Override
                    public void onResponse(Call<MusicBean> call, Response<MusicBean> response) {
                        MusicBean body = response.body();
                            new Thread(){
                                @Override
                                public void run() {
                                    for (MusicBean.ResultBean.TracksBean tracksBean : body.getResult().getTracks()) {
                                        Music musics = new Music();
                                        musics.setId(null);
                                        musics.setMp3url(tracksBean.getMp3Url());
                                        musics.setName(tracksBean.getAlbum().getArtists().get(0).getName());
                                        musics.setTime(tracksBean.getDuration());
                                        musics.setTitle(tracksBean.getName());
                                        musics.setPicurl(tracksBean.getAlbum().getPicUrl());
                                        ExampleApplication.getMusicDao().insertOrReplace(musics);
                                    }
                                }
                            }.start();
                        onMusicGetListener.onMusicSuccess(body.getResult());
                    }

                    @Override
                    public void onFailure(Call<MusicBean> call, Throwable t) {
                        onMusicGetListener.onMusicError(t);
                    }
                });
    }
}
